package com.example.config;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
@EnableScheduling
public class SchedulingConfig {

	@Autowired
	private Path audioStoragePath;

	@Scheduled(cron = "0 0 * * * *")
	public void cleanupOldFiles() {
		try {
			Files.list(audioStoragePath).filter(path -> {
				try {
					return Files.getLastModifiedTime(path).toInstant().plusSeconds(3600)
							.isBefore(java.time.Instant.now());
				} catch (IOException e) {
					return false;
				}
			}).forEach(path -> {
				try {
					Files.deleteIfExists(path);
				} catch (IOException e) {
					e.printStackTrace();
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
